package com.dq.protocol;

import com.dq.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName HttpClient
 * @Description Http客户端
 * @Author DuX1aoQiang
 * @Date 2023/5/24 12:17
 * @Version 1.0
 */
public class HttpClient {
    //发送数据
    public String send(String hostname, Integer port, Invocation invocation) throws IOException {
        //用户配置 并且选择发送请求方式 最原始的方式
        try {
            URL url = new URL("http", hostname, port, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            //配置
            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            //阻塞式获取
            InputStream inputStream = httpURLConnection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return result;
        } catch (IOException e) {
            throw e;
        }

    }
}
